<template>
  <div>
    <a-layout style="background: #ffffff">
      <a-skeleton active :loading="loadingSeller">
        <a-page-header
            :title="sellerData_menu.name"
            @back="() => $router.go(-1)"
            v-if="!loadingSeller"
        >
          <template slot="extra">
            <a-avatar :src="sellerData_menu.logo" shape="square"/>
          </template>
          <a-descriptions size="small" :column="3">
            <a-descriptions-item label="地址">
              {{sellerData_menu.address}}
            </a-descriptions-item>
            <a-descriptions-item label="营业时间">
              {{sellerData_menu.businessHour}}
            </a-descriptions-item>
            <a-descriptions-item label="营业执照">
              <a :href="sellerData_menu.licenseUrl" target="_blank">查看图片</a>
            </a-descriptions-item>
            <a-descriptions-item label="联系电话">
              {{sellerData_menu.phoneNum}}
            </a-descriptions-item>
            <a-descriptions-item label="距离">
              {{calcDistance(sellerData_menu.range)}}
            </a-descriptions-item>
          </a-descriptions>
        </a-page-header>
      </a-skeleton>
      <a-skeleton active :loading="loadingMenu">
        <a-layout style="background: #ffffff" v-if="!loadingMenu">
          <a-layout-sider theme="light" style="position: fixed">
            <a-menu
                style="width: 8vw"
                :default-selected-keys="['0']"
                @click="handleCateClick"
                :selectedKeys="menuCateSelected"
            >
              <template v-for="(item,index) in menuData.cateName">
                <a-menu-item :key="index">
                  {{item}}
                </a-menu-item>
              </template>
            </a-menu>
          </a-layout-sider>

          <a-layout style="margin-left: 10vw">
            <template v-for="(cate,cateIndex) in menuData.cateName">
              <a-card :title="cate" style="width: 100%" :id="'cateCard'+cateIndex">
                <a-list item-layout="horizontal" :data-source="dishFilter(cate)" :split="false">
                  <a-list-item slot="renderItem" slot-scope="item, index">
                    <template slot="actions">
                      <a-button type="primary" shape="circle" icon="minus" @click="delDish(item.dishName)"/>
                      {{getDishNum(item.dishName)}}
                      <a-button type="primary" shape="circle" icon="plus" @click="addDish(item.dishName)"/>
                    </template>
                    <a-list-item-meta :description="'￥'+item.singlePrice">
                      <a-avatar slot="avatar" :src="item.dishLogo"/>
                      <h3 slot="title">{{item.dishName}}</h3>
                    </a-list-item-meta>
                  </a-list-item>
                </a-list>
              </a-card>
              <div style="height: 1vw;background: #ffffff"/>
            </template>
            <a-row style="background: #ffffff">
              <a-col :span="22"/>
              <a-col :span="2">
                <a-affix :offset-bottom="50">
                  <a-popover placement="topRight">
                    <template slot="content">
                      <template v-for="(item,index) in userCart">
                        <h3>{{item.thingName+' ￥'+(item.thingNumber*item.singlePrice).toFixed(2)}}</h3>
                        <a-icon type="minus" @click="minuDish(index)"/>
                        {{item.thingNumber}}
                        <a-icon type="plus" @click="userCart[index].thingNumber++"/>
                      </template>
                      <p v-if="userCartSum==0" slot="content">空空如也</p>
                    </template>
                    <template slot="title">
                      <a @click="userCart=[]">清空</a>
                    </template>
                    <a-button icon="shopping-cart" type="primary" @click="gotoSubmit" :disabled="userCart.length==0">
                      {{'￥'+userCartSum}}
                      <a-icon type="right"/>
                    </a-button>
                  </a-popover>
                </a-affix>
              </a-col>
            </a-row>
          </a-layout>
        </a-layout>
      </a-skeleton>
    </a-layout>
    <a-modal v-model:visible="showLoginTip" title="尚未登录" @ok="handleLoginOK" okText="登录" cancelText="取消">
      <p>登录后方可提交订单，是否登录？</p>
    </a-modal>
  </div>
</template>

<script>
import {notification} from "ant-design-vue";
export default {
  name: "Menu",
  methods:{
    getMenuPageInfo:function (){
      if(this.sellerID==undefined) {
        this.sellerData_menu={
          address:'参数为空，调试模式'
        }
        return
      }
      let rearUrl=this.$store.state.rear_url

      //请求商家信息
      this.$axios.post('http://'+rearUrl+'/sellerinfo',{
        sellerID:this.sellerID
      }).then((response)=>{
        this.loadingSeller=false
            console.log(response.data)
            if(response.data.sellerInfoStatus!==0){
              notification.open({
                message:'请求商家信息失败',
                description:"请求商家信息时服务器返回了状态码1"
              })
            }else{
              this.sellerData_menu=response.data
            }
          })
          .catch((err)=>{
            this.loadingSeller=false
            notification.open({
              message:'请求商家信息失败',
              description:"服务器错误："+err.message
            })
          })

      //请求菜单
      this.$axios.post('http://'+rearUrl+'/menu',{
        sellerID:this.sellerID
      }).then((response)=>{
        this.loadingMenu=false
        console.log(response.data)
        if(response.data.menuInfoStatus!==0){
          notification.open({
            message:'请求菜单失败',
            description:"请求菜单时服务器返回了状态码1"
          })
        }else{
          this.menuData=response.data
        }
      })
          .catch((err)=>{
            this.loadingMenu=false
            notification.open({
              message:'请求菜单信息失败',
              description:"服务器错误："+err.message
            })
          })
    },
    dishFilter(cateName){
      let selectedDishes=[]
      this.menuData.dishes.forEach((dish)=>{
        if(dish.cateName==cateName) selectedDishes.push(dish)
      })
      return selectedDishes
    },
    handleCateClick(clickInfo){
      this.menuCateSelected=[clickInfo.key]
      document.getElementById('cateCard'+clickInfo.key).scrollIntoView()
    },
    cateAnchor(){
      if(this.loadingMenu||this.menuData==''||this.$route.path!='/menu'||document.getElementById('cateCard0')==undefined) return
      const documentClientHeight = document.documentElement.clientHeight || window.innerHeight
      let maxVisible
      this.menuData.cateName.forEach((cate,index)=>{
        if (documentClientHeight-10 >= document.getElementById('cateCard'+index).getBoundingClientRect().top) maxVisible=index
      })
      this.menuCateSelected=[maxVisible-2]
    },
    calcDistance:function (distance){
      if(this.loadingSeller) return
      if(distance>999) {
        return (distance/1000).toFixed(1).toString()+'km'
      }else return distance.toString()+'m'
    },
    minuDish:function (index){
      this.userCart[index].thingNumber--
      if(this.userCart[index].thingNumber<=0) {
        this.userCart.splice(index, 1)
      }
    },
    cartPush:function (dish,reqCode){
      let operated=false
      this.userCart.forEach((item,index)=>{
        if(item.thingName==dish.thingName){
          if(reqCode==0) this.userCart[index].thingNumber--
          else this.userCart[index].thingNumber++
          operated=true
        }
      })
      if(!operated){
        if(reqCode==0) {
          console.log("警告：尝试删除购物车中不存在的商品")
        }
        else this.userCart.push(dish)
      }
    },
    addDish:function (dishName){
      this.menuData.dishes.forEach((item,index)=>{
        if(item.dishName==dishName){
          this.cartPush({
            singlePrice: item.singlePrice,
            thingName:item.dishName,
            thingNumber:1,
            cartDishID:index,
            thingLogo:item.dishLogo
          },1)
        }
      })
    },
    delDish:function (dishName){
      this.userCart.forEach((item,index)=>{
        if(item.thingName==dishName) {
          this.minuDish(index)
        }
      })
    },
    getDishNum:function (dishName){
      let operated=false
      let retNum
      this.userCart.forEach((item)=>{
        if(item.thingName==dishName) {
          operated=true
          retNum=item.thingNumber
        }
      })
      return operated?retNum:0
    },
    gotoSubmit:function (){
      this.$store.commit('stuffCart',this.userCart)
      this.$store.commit('setSellerID',this.sellerID)

      //检查用户是否登录
      if(this.$store.state.userName==''){
        this.showLoginTip=true
      }else{
        window.location='/#/submit?sellerID='+this.sellerID
      }
    },
    handleLoginOK:function (){
      this.showLoginTip=false
      window.location='/#/login'
    }
  },
  data:function (){
    return {
      sellerID:'',
      loadingSeller:true,
      loadingMenu:true,
      sellerData_menu:'',
      menuCateSelected:[0],
      menuData:'',
      userCart:[],
      showLoginTip:false
    }
  },
  created() {
    if(this.$route.query.sellerID==undefined) {
    notification.open({
      message:'非法的页面请求',
      description:"无参数的菜单页面"
    })
    window.location='/#/'
    return
  }
    this.sellerID=this.$route.query.sellerID
    if(this.$store.state.sellerID==this.sellerID) this.userCart=this.$store.state.cart
    this.getMenuPageInfo()
    setInterval(this.cateAnchor,500)
  },
  computed:{
    userCartSum:function (){
      let sum=0
      this.userCart.forEach((item)=>{
        sum+=item.thingNumber*item.singlePrice
      })
      return sum.toFixed(2)
    }
  }
}
</script>

<style scoped>

</style>